<template>
  <el-dialog
    title="商户充值"
    :visible.sync="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    @closed="resetForm">
    
    <el-form
      ref="rechargeForm"
      :model="form"
      :rules="rules"
      label-width="80px">
      
      <!-- 商户信息 -->
      <el-form-item label="商户名称">
        <div>{{ merchantData.name }}</div>
      </el-form-item>
      
      <!-- 当前余额 -->
      <el-form-item label="当前余额">
        <div style="color: #E6A23C; font-weight: 500;">
          ¥{{ parseFloat(merchantData.balance || 0).toFixed(2) }}
        </div>
      </el-form-item>
      
      <!-- 充值说明 -->
      <el-form-item label="充值说明">
        <div style="color: #909399; font-size: 14px; line-height: 1.5;">
          点击"获取充值链接"将打开船到平台充值页面，请在新页面中完成充值操作。
          充值成功后，系统将自动更新商户余额。
        </div>
      </el-form-item>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="success"
        :loading="syncing"
        @click="syncBalance"
        style="margin-left: 8px;">
        <i class="el-icon-refresh"></i>
        同步余额
      </el-button>
      <el-button
        type="primary"
        :loading="submitting"
        @click="getRechargeUrl">
        获取充值链接
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { rechargeBalance, syncMerchantBalance } from '@/api/chuandao';

export default {
  name: 'MerchantRechargeDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 商户数据
    merchantData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      submitting: false,
      syncing: false,
      form: {},
      rules: {}
    };
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.resetForm();
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.submitting = false;
      this.syncing = false;
    },
    
    // 取消操作
    handleCancel() {
      this.dialogVisible = false;
    },
    
    // 获取充值链接并打开充值页面
    async getRechargeUrl() {
      console.log('充值按钮被点击了！');
      console.log('商户数据:', this.merchantData);

      this.submitting = true;

      try {
        const params = {
          merchant_id: this.merchantData.id
        };

        console.log('准备发送请求，参数:', params);

        const res = await rechargeBalance(params);

        console.log('API响应:', res);

        if (res.code === 200) {
          const rechargeUrl = res.data.recharge_url;

          if (rechargeUrl) {
            // 在新窗口打开充值页面
            window.open(rechargeUrl, '_blank');

            this.$message.success('充值页面已在新窗口打开，请完成充值操作');

            // 提示用户同步余额
            this.$confirm('充值完成后，是否同步商户余额？', '提示', {
              confirmButtonText: '同步余额',
              cancelButtonText: '稍后同步',
              type: 'info'
            }).then(() => {
              // 自动调用同步余额功能
              this.syncBalance();
            }).catch(() => {
              // 用户选择稍后同步，仅触发刷新事件
              this.$emit('recharge-success', {
                merchant_id: this.merchantData.id,
                refresh_balance: true
              });
            });

            this.dialogVisible = false;
          } else {
            this.$message.error('获取充值链接失败：链接为空');
          }
        } else {
          this.$message.error(res.message || '获取充值链接失败');
        }
      } catch (error) {
        console.error('获取充值链接失败:', error);
        this.$message.error('请求失败，请检查网络');
      } finally {
        this.submitting = false;
      }
    },

    // 同步商户余额
    async syncBalance() {
      if (!this.merchantData || !this.merchantData.id) {
        this.$message.error('商户信息错误');
        return;
      }

      this.syncing = true;

      try {
        const res = await syncMerchantBalance(this.merchantData.id);

        if (res.code === 200) {
          const syncData = res.data;
          const { sync_type, difference, platform_balance, local_balance_before, local_balance_after } = syncData;
          
          // 根据同步类型显示不同的消息
          if (sync_type === 'auto_recharge') {
            this.$message.success(`余额同步成功！自动充值¥${difference}，当前余额：¥${local_balance_after}`);
            
            // 触发余额更新事件
            this.$emit('recharge-success', {
              merchant_id: this.merchantData.id,
              new_balance: local_balance_after,
              sync_type: 'auto_recharge',
              amount: difference
            });

          } else if (sync_type === 'platform_lower') {
            this.$message.warning({
              message: `注意：平台余额(¥${platform_balance})低于本地余额(¥${local_balance_before})，请检查是否有未同步的消费记录`,
              duration: 5000
            });

          } else {
            this.$message.success(`余额已同步，当前余额：¥${local_balance_after}`);
          }

          // 可选：显示详细的同步结果
          this.$notify({
            title: '余额同步详情',
            message: `
              <div style="line-height: 1.5;">
                <p><strong>平台余额：</strong>¥${platform_balance}</p>
                <p><strong>本地余额：</strong>¥${local_balance_before}</p>
                ${sync_type === 'auto_recharge' ? `<p><strong>自动充值：</strong>¥${difference}</p>` : ''}
                <p><strong>同步后余额：</strong>¥${local_balance_after || local_balance_before}</p>
                <p><strong>同步时间：</strong>${syncData.sync_time}</p>
              </div>
            `,
            dangerouslyUseHTMLString: true,
            type: sync_type === 'auto_recharge' ? 'success' : 'info',
            duration: 8000
          });

        } else {
          this.$message.error(res.message || '同步余额失败');
        }

      } catch (error) {
        console.error('同步余额失败:', error);
        this.$message.error('同步请求失败，请检查网络连接');
      } finally {
        this.syncing = false;
      }
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>